package order.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.AllArgsConstructor;
import order.dto.FoodNutrition;
import order.dto.FoodTagResponse;
import order.dto.FoodTags;
import order.mapper.FoodNutritionMapper;
import order.mapper.FoodTagsMapper;
import org.apache.dubbo.config.annotation.DubboService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@AllArgsConstructor
@DubboService(version = "1.0.0")
public class FoodTagsImpl implements FoodTagsI {
    FoodTagsMapper foodTagsMapper;
    FoodNutritionMapper foodNutritionMapper;

   public List<FoodTags> getFoodTogs(int foodId){
       LambdaQueryWrapper<FoodTags> queryWrapper = new LambdaQueryWrapper<>();
       queryWrapper.eq(FoodTags::getFoodId, foodId);
       return foodTagsMapper.selectList(queryWrapper);
   }

    public List<FoodTagResponse>  getAllFoodTags() {
        List<FoodTags> foodTags = foodTagsMapper.selectList(null);

        // 不设置任何条件，表示获取所有记录
        return aggregateFoodTags(foodTags);
    }


   public List<FoodNutrition> getFoodTogsByFoodTag(String tag){
       // TODO: implement the logic to get the food tags by tag
       LambdaQueryWrapper<FoodTags> queryWrapper = new LambdaQueryWrapper<>();
       queryWrapper.eq(FoodTags::getTag, tag);
      List<Integer> foodIds = foodTagsMapper.selectList(queryWrapper).stream().map(FoodTags::getFoodId).distinct().collect(Collectors.toList());
      LambdaQueryWrapper<FoodNutrition> queryWrapper1 = new LambdaQueryWrapper<>();
      queryWrapper1.in(FoodNutrition::getId, foodIds);
      return foodNutritionMapper.selectList(queryWrapper1);
   }                                                                                                                                                                                    

   public  Boolean addFoodTag(int foodId, String tag){
       // TODO: implement the logic to add a food tag
       FoodTags foodTags = new FoodTags();
       foodTags.setFoodId(foodId);
       foodTags.setTag(tag);
       return foodTagsMapper.insert(foodTags) > 0;
   }



        public  List<FoodTagResponse> aggregateFoodTags(List<FoodTags> foodTags) {
            Map<String, List<Integer>> tagMap = new HashMap<>();

            for (FoodTags tag : foodTags) {
                tagMap.computeIfAbsent(tag.getTag(), k -> new ArrayList<>()).add(tag.getFoodId());
            }

            List<FoodTagResponse> responses = new ArrayList<>();
            for (Map.Entry<String, List<Integer>> entry : tagMap.entrySet()) {
                responses.add(new FoodTagResponse(entry.getKey(), entry.getValue()));
            }

            return responses;
        }


}
